class InfosController < ApplicationController
  before_filter :authorize_for_admin
  layout 'base.html', :except => [ :emails_spread, :sms_spread, :give_up]
  
  def index
    params[:info_type_id] ||= '%'
    @infos = Info.paginate :conditions => ['info_type_id like ?', params[:info_type_id]], :order => 'created_at desc', :page => 1, :per_page => 30
    @spreadeds_count = 0
    @infos.each do |info|
      @spreadeds_count +=1 if info.spreaded?
    end
    @seo_title = "麦吐司网-资讯管理"
    @seo_keywords = @seo_title
    @seo_description = @seo_title
  end
  
  def new
    @info = Info.create!( 
      :tool_id => params[:tool_id],
      :title => '未命名'
    )
    redirect_to edit_info_url(@info)
  end
  
  def edit
    @info = Info.find(params[:id])
    @seo_title = "麦吐司网-编辑资讯-#{@info.title}"
    @seo_keywords = @seo_title
    @seo_description = @seo_title
  end
  
  def update    
    @info = Info.find(params[:id])
    respond_to do |format|
      format.html do         
        @info.update_attributes(params[:info]) ? redirect_to(:action => :index) : render(:edit)
      end
      format.js do
        @info.update_attributes(params[:info]) ? render(:text => '保存成功', :status => 200) : render(:text => '保存失败', :status => 500)
      end
    end
  end
  
  def destroy
    @info = Info.find(params[:id])
    @info.destroy ? render(:text => '删除成功', :status => 200) : render(:text => '删除失败', :status => 500)
  end
  
  def show
    @info = Info.find(params[:id])
  end
  
  def emails_spread
    @info = Info.find(params[:id])
    @info.emails_spread_ready!
  end
  
  def sms_spread
    @info = Info.find(params[:id])
    @info.sms_spread_ready!
  end
  
  def give_up
    @info = Info.find(params[:id])
    if params[:give_up_type] == 'email'
      @info.give_up_emails_spread!
    else
      @info.give_up_sms_spread!
    end
  end
end
